<template>
  <div class="app">
    <el-upload
        class="avatar-uploader"
        action="api/User/uploadProfile"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :headers="{
          'Authorization' : this.getToken
        }"
        :data="{
          username:this.getUser.username,
          oldUserImg : this.getUser.userImg
        }"

    >
      <img v-if="this.getUser.userImg" :src="getUser.userImg | url" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>

    </div>
</template>

<script>


import {updateUser} from "@/utils/api";

export default {
  name: "UploadProfile",
  props: {},
  data() {
    return {
      fileList: []

    }
  }, methods: {
    async update(){
      // console.log(this.user)
      const user = this.getUser;
      updateUser(
          user
      ).then(res=>{
        if(res.code === 200){
          this.$notify.success("提交成功")
          // console.log(res)
        }else{
          this.$notify.error("提交失败")
          // console.error(res)
        }
      })
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      if(res.code ===200){
        this.userImg = res.objects
        this.$message.success("头像已更新")
        this.update()
      }else{
        this.$message.error("头像更新失败")
      }

    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }, watch: {}, computed: {
    getToken(){
      return localStorage.getItem('token')
    },
    userImg:{
      get(){
        return this.$store.getters.getUser.userImg;
      },
      set(value){
        var user = this.getUser
        user.userImg = value
        this.getUser = user
      }
    },
    getUser:{
      get(){
        return this.$store.getters.getUser;
      },
      set(value){
        return this.$store.commit("setUser",value);
      }
    }
  }, filters: {
    url(value){
      return 'api'+value;
    }
  }
}
</script>

<style scoped>
.app{
  width: 500px;
}
>>>.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
>>>.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
>>>.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
>>>.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>